package com.leetCode.zero;

import java.lang.reflect.Method;
import java.math.BigDecimal;

/**
 * 
 * You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
 * @author lyk
 *
 */
public class Problem02 {

	public static void main(String[] args) throws Exception {
		Solution s = getInstance();
		ListNode a = s.toListNode(new BigDecimal("9999999999"));
		ListNode b = s.toListNode(new BigDecimal("9999999999"));
		ListNode addTwoNumbers = s.addTwoNumbers(a,b);
		System.out.println(addTwoNumbers);
	}

	class Solution {
	    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
	    	BigDecimal a = toInteger(l1);
	    	BigDecimal b = toInteger(l2);
	    	BigDecimal sum = a.add(b);
	        return toListNode(sum);
	    }
	    public BigDecimal toInteger(ListNode ln){
	    	BigDecimal result = new BigDecimal(ln.val);
	    	if(ln.next != null){
	    		return result.add(toInteger(ln.next).multiply(new BigDecimal(10)));
	    	}else{
	    		return result;
	    	}
	    }
	    public ListNode toListNode(BigDecimal num){
	    	String s = num + "";
	    	String[] split = s.split("");
	    	ListNode result = new ListNode(0);
	    	ListNode temp = result;
	    	for (int i=split.length-1; i>=0; i--) {
	    		temp.next = new ListNode(Integer.parseInt(split[i]));
	    		temp = temp.next;
			}
	    	return result.next;
	    }
	}
	static Solution getInstance() throws Exception {
		String className = Thread.currentThread().getStackTrace()[1].getClassName();
		Class<?> forName = Class.forName(className);
		Method method = forName.getMethod("newS", null);
		Solution solution = (Solution) method.invoke(forName.newInstance(), null);
		return solution;
	}

	public Solution newS() {
		return new Solution();
	}
}
class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		if(next != null){
			return val+"-->"+next.toString();
		}else{
			return val+"";
		}
	}
}